import requests
import time
import hmac
import hashlib
import base64
import json


# 钉钉机器人发送消息
def send_dingtalk_message(webhook_url, secret, content, at_all=False):
    '''
    webhook_url: 钉钉机器人的webhook地址
    secret: 钉钉机器人的签名密钥
    content: 要发送的文本内容
    '''
    timestamp = str(round(time.time() * 1000))  # 当前时间戳（毫秒）
    string_to_sign = f"{timestamp}\n{secret}" # 待签名字符串
    hmac_code = hmac.new(
        secret.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256
    ).digest() # 计算签名
    signature = base64.b64encode(hmac_code).decode("utf-8") # 将签名进行base64编码
    url = f"{webhook_url}&timestamp={timestamp}&sign={signature}" # 拼接完整的URL
    # 构造消息内容
    message = {
        "msgtype": "text",
        "text": {"content": content},
        "at": {
            "atMobiles": [],  # 指定 @ 的手机号列表
            "isAtAll": at_all,  # 是否 @ 所有人
        },
    }
    headers = {"Content-Type": "application/json"} # 设置请求头
    response = requests.post(url, headers=headers, data=json.dumps(message)) # 发送POST请求
    # 判断请求是否成功
    if response.status_code == 200: # 判断请求是否成功
        print("消息发送成功！")
    else:
        print("消息发送失败！")


# 测试
if __name__ == "__main__":
    webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=a7dc0936981dc3b93e9ceb860f5db929976718c6db4a05e366201f343fe184b4"
    secret = "SEC77fc4b30c6434648d80b26fd9f666b7a1f0d1e126f83887cf004a281a3f599c9"
    content = "你好，这是一条测试消息！！"
    # 不 @ 所有人
    send_dingtalk_message(webhook_url, secret, content)

    # @ 所有人
    send_dingtalk_message(webhook_url, secret, content, at_all=True)
